import { Component, OnInit } from '@angular/core';
import {InventoryService} from "../inventory.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ConfirmationService} from "primeng/primeng";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-requestion-overview',
  templateUrl: './requestion-overview.component.html',
  styleUrls: ['./requestion-overview.component.scss']
})
export class RequestionOverviewComponent implements OnInit {
  cols;
  zh;
  queryModel;
  chooseCids =[];
  MaterialData;
  totalRecords;
  selectMaterial=[];
  statusNames;
  MaterialStatusData;
  constructor( private inventoryService:InventoryService,
               private router:Router,
               private route:ActivatedRoute,
               private eventBusService: EventBusService,
               private confirmationService: ConfirmationService) { }

  ngOnInit() {
    this.statusNames = [
      {label: '', value: ''},
      {label: '新建', value: '新建'},
      {label: '待审批', value: '待审批'},
      {label: '待出库', value: '待出库'},
      {label: '已完成', value: '已完成'},
      {label: '拒绝', value: '拒绝'},
      {label: '驳回', value: '驳回'},
    ]
    this.zh = {
      firstDayOfWeek: 1,
      dayNames: [ "周一","周二","周三","周四","周五","周六","周日" ],
      dayNamesShort: [ "一","二","三","四","五","六","七" ],
      dayNamesMin: [ "一","二","三","四","五","六","七" ],
      monthNames: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月" ],
      monthNamesShort: [ "一","二","三","四","五","六","七","八","九","十","十一","十二" ],
    };
    this.queryModel={
      "condition":{
        "sid": "",
        "location": "",
        "status": "",
        "begin_time": "",
        "end_time": "",
        "org": "",
        "creator": ""
      },
      "page":{
        "page_size":"10",
        "page_number":"1"
      }
    };
    this.cols = [
      // {field: 'sid', header: '领用单号'},
      // {field: 'type', header: '申请类型'},
      {field: 'creator', header: '领用人'},
      {field: 'org', header: '部门名称'},
      {field: 'status', header: '状态'},
      {field: 'approver', header: '审批人'},
      {field: 'audit_time', header: '审批时间'},
    ];
    this.eventBusService.updatereequipment.subscribe(
      data=>{
        this.queryModel.condition.status = data;
        this.queryMaterialDate();
      }
    )
    this.queryMaterialDate();

    this.queryMaterialStatusDate();
  }
  clearSearch() {
    this.queryModel.condition.begin_time = '';
    this.queryModel.condition.end_time = '';
    this.queryModel.condition.sid = '';
    this.queryModel.condition.org = '';
    this.queryModel.condition.creator = '';


  }
  //搜索功能
  suggestInsepectiones(){
    this.queryModel.page.page_number ='1'
    this.queryModel.page.page_size ='10';
    this.queryMaterialDate()
  }
  //分页查询
  paginate(event) {
    this.chooseCids =[]
    this.queryModel.page.page_number = String(++event.page);
    this.queryModel.page.page_size = String(event.rows);
    this.queryMaterialDate();
  }
  queryMaterialStatusDate(){
    this.inventoryService.queryReceiveStatus().subscribe(data=>{
      if(!data){
        this.MaterialStatusData = [];
      }else{
        this.MaterialStatusData = data;
        this.MaterialStatusData = this.inventoryService.formatDropdownData(this.MaterialStatusData)
        console.log(this.MaterialStatusData)
      }
    });
  }
  queryMaterialDate(){
    this.inventoryService.queryRequestionView(this.queryModel).subscribe(data=>{
      if(!data['items']){
        this.MaterialData = [];
        // this.selectMaterial =[];
        // this.totalRecords = 0;
      }else{
        this.MaterialData = data.items;
        console.log(this.MaterialData)
        this.totalRecords = data.page.total;
      }
    });
  }
  //审批
  borrowApproved(current){
    let sid = current['sid'];
    this.eventBusService.requstion.next(current.status);
    this.router.navigate(['../requisitionapproved'],{queryParams:{sid:sid},relativeTo:this.route})
  }
  // //确认出库
  // sureApproved(current){
  //   let sid = current['sid'];
  //   this.eventBusService.requstion.next(current.status);
  //   this.confirmationService.confirm({
  //     message: '确定出库吗?',
  //     accept: () => {
  //       this.inventoryService.queryBorrowSure(sid).subscribe(data=>{
  //         this.selectMaterial = [];
  //         this.queryMaterialDate();
  //       },(err:Error)=>{
  //         this.confirmationService.confirm({
  //           message: err['message'],
  //           rejectVisible:false,
  //         })
  //       })
  //     },
  //     reject:() =>{}
  //   })
  // }
  //编辑
  updateOption(current){
    let sid = current['sid'];
    this.eventBusService.requstion.next(current.status);
    this.router.navigate(['../requisition'],{queryParams:{sid:sid,state:'update',title:'编辑'},relativeTo:this.route})
  }
  //查看
  viewBorrowApproved(current){
    let sid = current['sid'];
    this.eventBusService.requstion.next(current.status);
    this.router.navigate(['../requisition'],{queryParams:{sid:sid,state:'viewDetail',title:'查看'},relativeTo:this.route})
  }
  //出库
  updateOutboundRequestion(current){
    let sid = current['sid'];
    this.eventBusService.requstion.next(current.status);
    this.router.navigate(['../requisition'],{queryParams:{sid:sid,state:'outboundRequestion',title:'出库'},relativeTo:this.route})
  }
  deleteMaterial(current){
    //请求成功后删除本地数据
    this.chooseCids = [];
    this.chooseCids.push(current['sid']);
    this.confirmationService.confirm({
      message:'确认删除吗？',
      accept: () => {
        this.inventoryService.deleteDelivery(this.chooseCids).subscribe(()=>{
          this.queryMaterialDate();
        },(err:Error)=>{
          let message ;
          if(JSON.parse(JSON.stringify(err)).status===0||JSON.parse(JSON.stringify(err)).status===504){
            message = '似乎网络出现了问题，请联系管理员或稍后重试'
          }else{
            message = err
          }
          this.confirmationService.confirm({
            message: message,
            rejectVisible:false,
          })
        })

      },
      reject:() =>{
      }
    });

  }

}
